-- UIEvilStatue
-- Created by cheny3 Sep/18/2016
-- 雕像

require "game/ui/form/equips/UIEquipTooltip"
require "game/ui/form/equips/UIEquips"

-- UIEvilStatue 继承自Layer
UIEvilStatue = class("UIEvilStatue", function()
    return cc.Layer:create();
end);

function UIEvilStatue.create(pos)
    return UIEvilStatue.new(pos);
end

-- 内部函数声明
local resize;
local MAX_SUBMIT_NUM = 3;

-- 构造函数
function UIEvilStatue:ctor(pos)
    self:setName("UIEvilStatue");

    -- 初始化(复用魔神雕像)
    local node = cc.CSLoader:createNode("layout/blacksmith/DemonStatue.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 记录格子的位置
    self.pos = pos;
    self.gridData = DungeonM.getGridByPos(pos);
    self.submited = {};

    -- 注册事件处理回调函数
    self:registerEventCallback()

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    resize(node);
end

-- 适配
function resize(node)
    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIEvilStatue:registerEventCallback()
    -- 关注工坊放入装备的事件
    EventMgr.register("UIEvilStatue", event.BLACKSMITH_INPUT_EQUIP, function(args)
        self:whenInputEquip(args);
    end);

    -- 关注献祭装备事件
    EventMgr.register("UIEvilStatue", event.EVIL_STATUE_SUBMIT, function(args)
        -- 清空
        self.submited = {};

        self:whenSubmit(args);
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIEvilStatue", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIEvilStatue" then
            self:checkDiaryBtn();
        elseif para["lose"] == "UIEvilStatue" then
            local btnDiary = findChildByName(self.node, "BT/btn_diary");
            btnDiary:setVisible(false);
        end
    end);

    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIEvilStatue 界面析构清理");
            EventMgr.removeAll("UIEvilStatue");

            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():showMenu();
                UIDungeonMgr:getCurLevel():showTop();
            end
        elseif eventType == "enter" then
            if UIDungeonMgr:getCurLevel() then
                UIDungeonMgr:getCurLevel():hideMenu();
                UIDungeonMgr:getCurLevel():hideTop();
            end
        end
    end);
end

-- 注册点击事件
function UIEvilStatue:registerTouchEvent()
    local node = self.node;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 先把选择框中脱下来的装备穿上去
            for index = 1, MAX_SUBMIT_NUM do
                local info = self.submited[index] or {};
                local classId = info.class_id;
                local isUnequiped = info.isUnequiped;

                if type(classId) == "number" and isUnequiped then
                    DungeonActionM.go("do_equip", 0, classId);
                end
            end

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIEvilStatue");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);

    -- 注册确定按钮点击事件
    local btnOk = findChildByName(node, "CT/btn_ok");
    local function onOkClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_confirm");
            -- 判断是否放入装备
            -- 取出所有提交的装备的class_id
            local submitList = {};

            for index = 1, MAX_SUBMIT_NUM do
                local info = self.submited[index] or {};
                if type(info.class_id) == "number" then
                    table.insert(submitList, info.class_id);
                end
            end

            -- 判断是否放入装备
            if #submitList <= 0 then
                alert(getLocStr("need_any_equip"));
                return;
            end

            -- submitList处理成数字
            local arg = EvilStatueM.changeItemsToArgs(submitList);

            -- 调用回调处理
            DungeonActionM.go("evil_statue_submit", self.pos, arg);
        end
    end

    btnOk:addTouchEventListener(onOkClick);

    -- 注册装备点击格点击事件，固定3个
    for index = 1, MAX_SUBMIT_NUM do
        local equipGrid = findChildByName(node, string.format("CT/submit_node%d/frame", index));
        local function onEquipClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                AudioM.playFx("button_click");
                -- 取出所有提交的装备的class_id
                local hasSubmitList = {};
                for index = 1, MAX_SUBMIT_NUM do
                    local info = self.submited[index] or {};
                    if type(info.class_id) == "number" then
                        table.insert(hasSubmitList, info.class_id);
                    end
                end

                -- 取出所有可提交的装备的class_id
                local submitList = EvilStatueM.getSubmitItems(self.gridData.classify);

                -- 打开装备选择界面
                -- 传入参数：通过指定提交方式打开
                local uiEquip = UIEquips.create(EQUIP_OPEN_TYPE_APPOINT_ITEMS,
                    {["index"] = index, ["submited"] = submitList, ["has_submited"] = hasSubmitList});
                UIMgr.getCurrentScene():addForm(uiEquip);
            end
        end
        equipGrid:addTouchEventListener(onEquipClick);
    end

    -- 注册传记按钮点击事件
    local btnDiary = findChildByName(self.node, "BT/btn_diary");
    local function onDiaryBtnClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");

            local data = EvilStatueM.queryStatue(self.gridData.classify, 1);

            -- 打开书籍界面
            local uiForm = UIBookInfo.create(data["book"]);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end
    btnDiary:addTouchEventListener(onDiaryBtnClick);
    TextStyleM.setTextStyle(btnDiary, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnDiary:setTitleText(getLocStr("btn_text_diary"));
end

-- 重绘
function UIEvilStatue:redraw()
    local CT = findChildByName(self.node, "CT");
    local BT = findChildByName(self.node, "BT");

    -- 玩家当前的信息
    local class = self.gridData.classify;
    local statueInfo = EvilStatueM.getStatueInfo(class);
    local level = statueInfo["cur_level"] or 0;
    local fixLevel = iif(level > 0, level, 1);
    local nextLevel = level + 1;
    local data = EvilStatueM.queryStatue(class, fixLevel);
    local exp = statueInfo["exp"];

    if not EvilStatueM.queryStatue(class, nextLevel) then
        nextLevel = level;
    end

    -- 显示标题
    local title;
    local name = BuildingBonusM.queryBuildingView(self.gridData.class, "title");
    if type(name) == "string" and name ~= "" then
        -- 如果配置了标题，直接使用
        title = name;
    else
        -- 使用雕像名字
        title = string.format(data["name"]);
    end

    local titleLabel = findChildByName(CT, "title_node/title");
    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_CYAN, true);
    titleLabel:setString(title)
    TextStyleM.setArtWordTitleStyle(titleLabel);

    -- 显示功能描述
    local desc = data.statue_desc or "";
    local descLabel = findChildByName(CT, "desc_node/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(descLabel, desc);

    -- 显示当前信仰等级
    local levelLabel = findChildByName(CT, "level");
    TextStyleM.setTextStyle(levelLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, true);
    levelLabel:setString(string.format(getLocStr("demon_level"), level));
    levelLabel:setPositionY(50);

    -- 显示建筑图标
    local mainIcon = findChildByName(CT, "icon");
    local icon = data.icon or "";
    mainIcon:loadTexture(getLevelItemIconPath(icon));
    mainIcon:setPositionY(100);

    -- 提交框
    local submitImgs = {};
    for index = 1, MAX_SUBMIT_NUM do
        local equipGrid = findChildByName(CT, string.format("submit_node%d/item_icon", index));
        submitImgs[index] = equipGrid;
    end
    self.submitImgs = submitImgs;

    self:redrawEquip();

    -- 显示提示
    local nextData = EvilStatueM.queryStatue(class, nextLevel);
    local requireExp = iif(nextData["exp"] > exp, nextData["exp"] - exp, 0);
    local tip = string.format(getLocStr("demon_tip"), data.name, data.god_name, requireExp);

    if EvilStatueM.isTopLevel(class) then
        tip = string.format(getLocStr("demon_max_level_tip"), data.name, data.god_name, requireExp);
    end

    local tipLabel = findChildByName(CT, "tip_node/text_tip");
    TextStyleM.setTextStyle(tipLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    applyString(tipLabel, tip);

    -- 显示确定按钮
    local btnOk = findChildByName(CT, "btn_ok");
    local okText = "";

    if #table.values(self.submited) > 0 and not EvilStatueM.isTopLevel(class) then
        -- 取出所有提交的装备的class_id
        local submitList = {};

        for index = 1, MAX_SUBMIT_NUM do
            local info = self.submited[index] or {};
            if type(info.class_id) == "number" then
                table.insert(submitList, info.class_id);
            end
        end

        okText = string.format(getLocStr("sacrifice_text"), EvilStatueM.calcItemsExp(submitList));

        btnOk:setBright(true);
        btnOk:setTouchEnabled(true);
    else
        okText = getLocStr("sacrifice_text2");

        btnOk:setBright(false);
        btnOk:setTouchEnabled(false);
    end

    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(okText);

    -- 日记按钮
    local btnDiary = findChildByName(self.node, "BT/btn_diary");
    local bookId = data["book"];

    -- 如果玩家包裹中没有日记，则不显示日记按钮
    self:checkDiaryBtn();

    -- 显示返回按钮
    local btnBack = findChildByName(BT, "btn_back");
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
end

-- 检测传记按钮是否显示
function UIEvilStatue:checkDiaryBtn()
    -- 玩家当前的信息
    local class = self.gridData.classify;
    local data = EvilStatueM.queryStatue(class, 1);

    -- 日记按钮
    local btnDiary = findChildByName(self.node, "BT/btn_diary");
    local bookId = data["book"];

    -- 否则如果玩家包裹中没有日记，则不显示日记按钮
    if ItemM.getAmount(ME.user, bookId) > 0 then
        btnDiary:setTitleText(getLocStr("btn_text_biography"));
        btnDiary:setVisible(true);
    else
        btnDiary:setVisible(false);
    end
end

-- 找出相同物品的id
function UIEvilStatue:filterSame(items)
    for index = 1, #items do
        local classId = items[index];
        local temp = table.deepcopy(items);
        table.remove(temp, index);
        if table.indexOf(temp, classId) >= 0 then
            -- 只有三个物品，找到有一样的就返回
            return classId;
        end
    end
    return 0;
end

-- 重绘装备格
function UIEvilStatue:redrawEquip()
    -- 取出所有提交的装备的class_id
    local submitList = {};

    for index = 1, MAX_SUBMIT_NUM do
        local info = self.submited[index] or {};
        if type(info.class_id) == "number" then
            table.insert(submitList, info.class_id);
        end
    end

    -- 提交一样的
    local sameClass = self:filterSame(submitList);

    for index = 1, MAX_SUBMIT_NUM do
        local submited = self.submited or {};
        local frame = findChildByName(self.node, string.format("CT/submit_node%d/frame", index));

        local classId;
        if not submited[index] then
            self.submitImgs[index]:setVisible(false);
            playLearnSkillHintEffect(frame, 70, 70);
        else
            self.submitImgs[index]:setVisible(true);
            classId = submited[index].class_id;
            local icon = ItemM.query(classId, "icon");
            self.submitImgs[index]:loadTexture(getItemIconPath(icon));

            self.submitImgs[index]:stopAllActions();
            self.submitImgs[index]:removeAllChildren();

            frame:removeAllChildren();
        end

        if classId and sameClass == classId then
            self.submitImgs[index]:stopAllActions();
            self.submitImgs[index]:removeAllChildren();

            frame:removeAllChildren();
            playEffect(self.submitImgs[index], 1265, 50, 50, nil, 1.2);
        end
    end
end

-- 工坊放入装备的回调
function UIEvilStatue:whenInputEquip(args)
    local equipId = args.classId;
    local isEquiped = args.isEquiped;
    local index = args.index;
    if not equipId or not index then
        return;
    end

    -- 记录装备id
    local submited = self.submited or {};
    local lastEquip = submited[index] or {};
    submited[index] = { ["class_id"] = equipId, ["isUnequiped"] = isEquiped, };
    self.submited = submited;

    -- 如果之前这个格子放了脱下来的装备，那么要穿回去
    if lastEquip.isUnequiped then
        DungeonActionM.go("do_equip", 0, lastEquip);
    end

    -- 重绘装备格
    self:redraw();
end

-- 雕像献祭的回调
function UIEvilStatue:whenSubmit(args)
    local isUpgrade = args.isUpgrade;
    local effectNode1 = findChildByName(self.node, "CT/effect_node1");
    local effectNode2 = findChildByName(self.node, "CT/effect_node2");

    local classify = args.classify;
    local data = EvilStatueM.queryStatue(classify, 1);
    local name = data["name"] or "";

    if isUpgrade then
        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName("UIEvilStatue");
    else
        -- “成功献祭黑夜女士雕像！”
        alert(string.format(getLocStr("submit_succ"), name));

        playEffect(effectNode1, 1264, -18, 190, nil, 1.3);
        playEffect(effectNode2, 1263, -20, 180, nil, 1.3);

        performWithDelay(self.node, function ()
            playEffect(effectNode1, 1264, -18, 190, nil, 1.3);
            playEffect(effectNode2, 1263, -20, 180, nil, 1.3);
        end, 0.4);

        -- 音效
        AudioM.playFx("immolation1");

        -- 刷新下
        self:redraw();
    end
end
